import MedicalRecord from '../models/medicalRecord.js'
import Medication from '../models/medication.js'
import Result from '../utils/result.js'

const diagnoseServices = {
  async addMedicalRecord(userData) {
    try {
      if(!userData.patientid){
        return Result.error('patientid不能为空');
      }
      const data = await MedicalRecord.create(userData);
      return Result.success(data, '添加病例成功').toObject();
    } catch (error) {
      return Result.error(error.message);
    };

  },

  async getMedicalRecord(patientid) {
    try {

      const data = await MedicalRecord.findAll({
        where: {
          patientid: patientid,
        }
      });
      return Result.success(data, '获得病例成功');
    } catch (error) {
      return Result.error(error.message);
    }
  },
  async delMedicalRecord(id) {
    try {
      const data = await MedicalRecord.findOne({
        where: {
          id: id
        }
      });
      if (!data) {
        return Result.notfound('病例不存在');
      }
        await data.destroy();
      return Result.success(id, '删除病例成功').toObject();
    } catch (error) {
      return Result.error(error.message);
    };
  },

  async addMedication(userData) {
    if (!userData.patientid || !userData.medicationName) {
      return Result.error('缺少必要参数');
    }
    try {
      const data = await Medication.create(userData);
      return Result.success(data, '添加用药记录成功').toObject();
    } catch (error) {
      return Result.error(error.message);
    };

  },
  async getMedication(patientid) {
    try {
      const data = await Medication.findAll({
        where: {
          patientid: patientid,
        }
      });
      return Result.success(data, '获得病例成功');
    } catch (error) {
      return Result.error(error.message);
    }
  },
  async delMedication(id) {
    try {
      const data = await Medication.findOne({
        where: {
          id: id
        }
      });
      if (!data) {
        return Result.error('用药记录不存在');
      }

      // 删除数据,返回值为删除的行数
      await data.destroy();

      return Result.success(id, '删除用药记录成功');
    } catch (error) {
      return Result.error(error.message);
    };
  }
}
export default diagnoseServices
